package design.factory;

import design.CacheService;
import design.factory.impl.EGMCacheAdapter;
import design.impl.CacheServiceImpl;
import design.util.ClassLoaderUtils;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * @author: hero生仔
 * 动态代理的核心，该类会处理对代理对象的所有方法的调用
 *
 * 把原有操作 Redis 的方式进行代理操作，通过控制不同的入参对象，控制缓存的使用
 */
public class JDKInvocationHandler implements InvocationHandler {
    /**
     * 我们需要对该接口的实例进行代理，所以我们抽象一下，对这个接口进行代理即可完成对实现该接口的实例进行代理
     */
    private ICacheAdapter cacheAdapter;

    public JDKInvocationHandler(ICacheAdapter iCacheAdapter) {
        this.cacheAdapter = iCacheAdapter;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        // 与 method.invoke() 的区别
        return ICacheAdapter.class.getMethod(method.getName(), ClassLoaderUtils.getClazzByArgs(args)).invoke(cacheAdapter, args);
    }
}

class Main {
    public static void main(String[] args) {
        JDKInvocationHandler handler = new JDKInvocationHandler(new EGMCacheAdapter());
        CacheService proxy_EGM = (CacheService) Proxy.newProxyInstance(ICacheAdapter.class.getClassLoader(), CacheServiceImpl.class.getInterfaces(), handler);
        proxy_EGM.set("user_name_01", "lds");
        String userName = proxy_EGM.get("user_name_01");
        System.out.println("测试结果：" + userName);
    }
}
